local json = require("json")

local deviceNameMapping = {
    ["0xEC1BBDFFFE368F16-1"] = "主卧空调",
    ["0xEC1BBDFFFEA3318A-1"] = "客厅空调",
}

local command_map = {
    ["0xEC1BBDFFFE368F16-1"] = "send 0xFE72 1 1", --主卧空调
    ["0xEC1BBDFFFEA3318A-1"] = "send 0x48CB 1 1" --客厅空调
}

--空调温度映射表
local vrf_temp_mapping = {
    ["0x110029540B"] = 29,
    ["0x110029F00A"] = 28,
    ["0x1100298C0A"] = 27,
    ["0x110029280A"] = 26,
    ["0x110029C409"] = 25,
    ["0x1100296009"] = 24,
    ["0x110029FC08"] = 23,
    ["0x1100299808"] = 22,
    ["0x1100293408"] = 21,
    ["0x110029D007"] = 20,
    ["0x1100296C07"] = 19,
    ["0x1100290807"] = 18,
}

--空调风速映射表
local fan_speed_mapping = {
    ["0x00003001"] = 1, --低
    ["0x00003002"] = 2, --中
    ["0x00003003"] = 3, --高
    ["0x00003005"] = 5, --自动
}
-- 空调模式匹配
local vrf_mode_mapping = {
    ["0x1C003003"] = 1, --制冷
    ["0x1C003004"] = 2, --制热
    ["0x1C003008"] = 3, --除湿
}

function isMapEmpty(map)
    for _, _ in pairs(map) do
        return false
    end
    return true
end
-- decode 请求数据解码
function decode(raw)
    local data = json.decode(raw)
    local payload = json.decode(data["payload"])
    local devices = {}
    local device = {}

    --if payload["clusterId"] == "0x0006" then
    --    return "[]"
    --end

    -- 判断raw是否包含EC1BBDFFFE368F16
    if data.topic == "gw/804B50FFFEE7BB91/zclresponse" and payload["deviceEndpoint"]["eui64"] == "0xEC1BBDFFFE368F16" then
        print("zclresponse: " .. raw)
    end

    -- 控制响应
    if data.topic == "gw/804B50FFFEE7BB91/zclresponse" and payload["commandId"] == "0x0A" then
        key = payload["deviceEndpoint"]["eui64"] .. "-" .. payload["deviceEndpoint"]["endpoint"]
        name = deviceNameMapping[key]
        if name == nil then
            return "[]"
        end
        device['id'] = key;

        if payload['commandData'] == "0x1C00300A" then
            device['values'] = {
                { ["name"] = 'onOff', ["value"] = '1' },
            }
        elseif payload['commandData'] == "0x1C003000" then
            device['values'] = {
                { ["name"] = 'onOff', ["value"] = '0' },
            }
        else
            -- 空调温度匹配
            tempSetting = vrf_temp_mapping[payload['commandData']]
            if tempSetting ~= nil then
                device['values'] = {
                    { ["name"] = 'tempSetting', ["value"] = tempSetting },
                }
            end
            --空调风速匹配
            fanSpeedSetting = fan_speed_mapping[payload['commandData']]
            if fanSpeedSetting ~= nil then
                device['values'] = {
                    { ["name"] = 'fanSpeedSetting', ["value"] = fanSpeedSetting },
                }
            end
            --空调模式匹配
            runMode = vrf_mode_mapping[payload['commandData']]
            if runMode ~= nil then
                device['values'] = {
                    { ["name"] = 'runMode', ["value"] = runMode },
                }
            end
            print("kkkk: " .. payload['commandData'])
        end
        print("device: " .. json.encode(device))

        device["events"] = {
            {
                ["code"] = "deviceDiscover",
                ["value"] = {
                    ["modelKey"] = "smarthome_vrf",
                    ["device"] = {
                        ["id"] = key,
                        ["description"] = name,
                    }
                }
            }
        }
        table.insert(devices, device)
    end

    -- 状态同步
    if data.topic == "gw/804B50FFFEE7BB91/zclresponse" and payload["attributeId"] ~= nil then
        key = payload["deviceEndpoint"]["eui64"] .. "-" .. payload["deviceEndpoint"]["endpoint"]
        name = deviceNameMapping[key]
        if name == nil then
            return "[]"
        end
        device['id'] = key;
        --if key == "0xEC1BBDFFFEA3318A-1" then
        print("zclresponse: " .. raw)
        --end

        -- 设定温度
        if payload["attributeId"] == "0x0011" and payload["attributeDataType"] == "0x29" then
            tempSetting = vrf_temp_mapping["0x001129" .. string.sub(payload["attributeBuffer"], 3)]
            if tempSetting ~= nil then
                device['values'] = {
                    { ["name"] = 'tempSetting', ["value"] = tempSetting },
                }
            end
        end

        -- 运行模式
        if payload["attributeId"] == "0x001C" and payload["attributeDataType"] == "0x30" then
            runMode = vrf_mode_mapping["0x1C0030" .. string.sub(payload["attributeBuffer"], 3)]
            if runMode ~= nil then
                device['values'] = {
                    { ["name"] = 'runMode', ["value"] = runMode },
                }
            end
        end

        --风速
        if payload["attributeId"] == "0x0000" and payload["attributeDataType"] == "0x30" then
            fanSpeedSetting = fan_speed_mapping["0x000030" .. string.sub(payload["attributeBuffer"], 3)]
            if fanSpeedSetting ~= nil then
                device['values'] = {
                    { ["name"] = 'fanSpeedSetting', ["value"] = fanSpeedSetting },
                }
            end
        end

        -- 开关
        if payload["attributeId"] == "0x001C" and payload["attributeDataType"] == "0x30" then
            if payload["attributeBuffer"] == "0x00" then
                device['values'] = {
                    { ["name"] = 'onOff', ["value"] = '0' },
                }
            else
                if payload["attributeBuffer"] == "0x0A" then
                    device['values'] = {
                        { ["name"] = 'onOff', ["value"] = '1' },
                    }
                end
            end
        end
        print("device: " .. json.encode(device))

        device["events"] = {
            {
                ["code"] = "deviceDiscover",
                ["value"] = {
                    ["modelKey"] = "smarthome_vrf",
                    ["device"] = {
                        ["id"] = key,
                        ["description"] = name,
                    }
                }
            }
        }
        table.insert(devices, device)
    end

    --if data.topic ~= 'gw/804B50FFFEE7BB91/commands' then
    --    return '[]'
    --end

    print("decodeResult:" .. json.encode(devices))
    return json.encode(devices)
end

function encode(device_name, rw, points)
    if rw == "read" then
        print("unsupport read...")
        return "{}"
    end
    if not device_name then
        print("device name not found")
        return "{}"
    end

    local result = {

    }

    local commandCli = command_map[device_name]
    if commandCli == nil then
        print("commandCli not found, device: " .. device_name)
        return "{}"
    end

    for _, command in pairs(points) do
        local pointName = command['name']
        local value = command['value']
        print("write pointName: " .. pointName .. " value:" .. value)
        -- 开关
        local commands = {}
        if pointName == 'onOff' then
            if value == 0 then
                table.insert(commands, {
                    ["commandcli"] = "raw 0x0201 {005e021c003000}", --关闭
                })
            else
                table.insert(commands, {
                    ["commandcli"] = "raw 0x0201 {002a021c00300a}", -- 打开
                })
            end
            table.insert(commands, {
                ["commandcli"] = commandCli,
                ["postDelayMs"] = 300
            })
            table.insert(result, {
                ["topic"] = "gw/804B50FFFEE7BB91/commands",
                ["payload"] = json.encode({ ["commands"] = commands })
            })
        end

        -- 设置风速
        if pointName == 'fanSpeedSetting' then
            if value == 1 then
                table.insert(commands, {
                    ["commandcli"] = "raw 0x0202 {001a0200003001}", --低风速
                })
            elseif value == 2 then
                table.insert(commands, {
                    ["commandcli"] = "raw 0x0202 {001d0200003002}", --中风速
                })
            elseif value == 3 then
                table.insert(commands, {
                    ["commandcli"] = "raw 0x0202 {001c0200003003}", --高风速
                })
            else
                table.insert(commands, {
                    ["commandcli"] = "raw 0x0202 {001e0200003005}", --自动风
                })
            end
            table.insert(commands, {
                ["commandcli"] = commandCli,
                ["postDelayMs"] = 300
            })
            table.insert(result, {
                ["topic"] = "gw/804B50FFFEE7BB91/commands",
                ["payload"] = json.encode({ ["commands"] = commands })
            })
        end

        -- 设置温度
        if pointName == 'tempSetting' then
            for key, v in pairs(vrf_temp_mapping) do
                if v == value then
                    -- key 去除头部两位，并转小写字母
                    key = string.lower(key)
                    key = string.sub(key, 3, -1)
                    table.insert(commands, {
                        ["commandcli"] = "raw 0x0201 {002002" .. key .. "}",
                    })
                    break
                end
            end
            table.insert(commands, {
                ["commandcli"] = commandCli,
                ["postDelayMs"] = 300
            })
            table.insert(result, {
                ["topic"] = "gw/804B50FFFEE7BB91/commands",
                ["payload"] = json.encode({ ["commands"] = commands })
            })
        end

        -- 设置模式
        if pointName == 'runMode' then
            if value == 1 then
                -- 制冷
                table.insert(commands, {
                    ["commandcli"] = "raw 0x0201 {0024021c003003}",
                })
            elseif value == 2 then
                --制热
                table.insert(commands, {
                    ["commandcli"] = "raw 0x0201 {0025021c003004}",
                })
            elseif value == 3 then
                --除湿
                table.insert(commands, {
                    ["commandcli"] = "raw 0x0201 {0023021c003008}",
                })
            end
            table.insert(commands, {
                ["commandcli"] = commandCli,
                ["postDelayMs"] = 300
            })
            table.insert(result, {
                ["topic"] = "gw/804B50FFFEE7BB91/commands",
                ["payload"] = json.encode({ ["commands"] = commands })
            })
        end
    end

    print("control:" .. json.encode(result))
    return json.encode(result)
end